package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.ReportService;
import com.itheima.health.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("report")
@Slf4j
public class ReportController {
    @DubboReference
    MemberService memberService;
    @DubboReference
    OrderService orderService;
    @DubboReference
    ReportService reportService;

    /**
     * @Author: JASON
     * @Date: 16:23 2021/1/15
     * @Parms []
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 根据月份查询会员用户增长折线图
    */
    @GetMapping("getMemberReport")
    public Result getMemberReport(){
        //月份
        List<String> months = new ArrayList<>();
        List<Integer> memberCount = null;
        //date ->传输  calendar ->日期处理
        Calendar calendar = Calendar.getInstance();
        //对当前月份 减12个月   回退到前12个月
        calendar.add(Calendar.MONTH,-12);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM");
        for (int i = 0; i < 12; i++) {
            Date date = calendar.getTime();
            String format = sdf.format(date);
            months.add(format);
            //获取完时间以后对月份加1  写正数就是加  负数就是减
            calendar.add(Calendar.MONTH,1);
        }
        //会员统计   快速构建  list：Arrays.asList（） Arrays.asList(1, 2, 3, 4, 5, 6, 100);
        memberCount = memberService.countByMonth(months);
        log.info("会员增长数"+memberCount);
        //封装返回结果
        HashMap<String, Object> map = new HashMap<>();
        map.put("months", months);
        map.put("memberCount", memberCount);
        return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    /**
     * @Author: JASON
     * @Date: 16:31 2021/1/15
     * @Parms []
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 获取套餐  预约人数占比
    */
    @GetMapping("getSetmealReport")
    public Result getSetmealReport(){
        //匿名内部类 加代码块
       /* List<Map<String, Object>> setmealCount = Arrays.asList(
                    new HashMap<String,Object>(){{put("name","入职体检");put("value",10);}},
                    new HashMap<String,Object>(){{put("name","入职体检");put("value",10);}},
                    new HashMap<String,Object>(){{put("name","入职体检");put("value",10);}}
        );
        //Stream流+Lamba表达式
        List<String> setmealName = setmealCount.stream().map(e -> (String) e.get("name")).collect(Collectors.toList());
*/

        List<Map<String, Object>> setMealCount = null;
        setMealCount = orderService.countBySetMeal();
        log.info("查询结果为"+setMealCount);
        ArrayList<String> setMealNames = new ArrayList<>();
        for (Map<String, Object> map : setMealCount) {
            setMealNames.add(String.valueOf(map.get("name")));
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("setmealNames", setMealNames);
        map.put("setmealCount", setMealCount);
        return new Result(true, MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
    }

    /**
     * @Author: JASON
     * @Date: 9:16 2021/1/16
     * @Parms []
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 运营报表
    */
    @GetMapping("getBusinessReportData")
    public Result getBusinessReportData(){
        Map<String, Object> map = reportService.getBussinessReport();
        return new Result(true,MessageConst.GET_BUSINESS_REPORT_SUCCESS,map);
    }


    /**
     * @Author: JASON
     * @Date: 14:35 2021/1/16
     * @Parms []
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 下载运营数据excel
    */
    @GetMapping("exportBusinessReport")
    public Result exportBusinessReport(HttpServletResponse response){
      //获取数据（查询service）
        Map<String, Object> reportData = reportService.getBussinessReport();
        //数据填入excel
        log.info("[报表-导出运营数据]data：{}",reportData);
        // 取出返回结果
        String reportDate = (String) reportData.get("reportDate");
        // 获取会员相关数据
        Long todayNewMember = (Long) reportData.get("todayNewMember");
        Long thisWeekNewMember = (Long) reportData.get("thisWeekNewMember");
        Long thisMonthNewMember = (Long) reportData.get("thisMonthNewMember");
        Long totalMember = (Long) reportData.get("totalMember");
        // 获取预约相关数据
        Long todayOrderNumber = (Long) reportData.get("todayOrderNumber");
        Long thisWeekOrderNumber = (Long) reportData.get("thisWeekOrderNumber");
        Long thisMonthOrderNumber = (Long) reportData.get("thisMonthOrderNumber");
        // 获取到诊相关数据
        Long todayVisitsNumber = (Long) reportData.get("todayVisitsNumber");
        Long thisWeekVisitsNumber = (Long) reportData.get("thisWeekVisitsNumber");
        Long thisMonthVisitsNumber = (Long) reportData.get("thisMonthVisitsNumber");
        // 获取套餐数据
        List<Map> hotSetmeal = (List<Map>) reportData.get("hotSetmeal");
        log.info("火热套餐数据为{}",hotSetmeal);

        //打开模板
        //打开类路径下的文件 ： 1.找到类加载器   2.调用类加载器读取文件
        //加载try小括号中调用完成之后执行close
        Workbook workbook = null;
        try(InputStream is= ReportController.class.getClassLoader().getResourceAsStream("report_template.xlsx");
            ServletOutputStream os = response.getOutputStream()
        ) {
             workbook= new XSSFWorkbook(is);
            Sheet sheet = workbook.getSheetAt(0);
            //填充日期   第2行第5列
            sheet.getRow(2).getCell(5).setCellValue(reportDate);
            sheet.getRow(4).getCell(7).setCellValue(totalMember);
            sheet.getRow(5).getCell(5).setCellValue(thisWeekNewMember);
            sheet.getRow(5).getCell(7).setCellValue(thisMonthNewMember);
            //填充预约数据
            sheet.getRow(7).getCell(5).setCellValue(todayOrderNumber);
            sheet.getRow(7).getCell(7).setCellValue(todayVisitsNumber);
            sheet.getRow(8).getCell(5).setCellValue(thisWeekOrderNumber);
            sheet.getRow(8).getCell(7).setCellValue(thisWeekVisitsNumber);
            sheet.getRow(9).getCell(5).setCellValue(thisMonthOrderNumber);
            sheet.getRow(9).getCell(7).setCellValue(thisMonthVisitsNumber);

            int rowNum = 12;
            //循环填入热门套餐
            for (Map map : hotSetmeal) {
                Row row = sheet.getRow(rowNum);
                row.getCell(4).setCellValue(String.valueOf((String)map.get("name")));
                row.getCell(5).setCellValue((long)map.get("setmeal_count"));
                //(BigDecimal).doubleValue()  转换成double
                row.getCell(6).setCellValue(((BigDecimal)map.get("proportion")).doubleValue());
                rowNum++;
            }

            //文件下载到客户端
            //设置响应头   把流放到请求体中
            response.setContentType("application/vnd.ms-excel");
            //指定保存文件名    attachment :告诉浏览器要保存文件
            response.setHeader("content-disposition","attachment;fileName=report"+reportDate+".xlsx");
            //把流输出到响应体中
            workbook.write(os);
        }catch (IOException e){
            log.error("",e);
            return new Result(true, MessageConst.GET_BUSINESS_REPORT_FAIL);
        }
        return null;
    }
}
